<?php

namespace app\controller\wmapi\examineapprove;

use app\controller\wmapi\IndexController;
use app\controller\wmapi\message\MessageNotifyController;
use app\controller\wmapi\order\OrderPurchaseController;
use app\model\WaChannel;
use app\model\WaDepartment;
use app\model\WaOrders;
use app\model\WaOrdersPurchase;
use app\model\WaOrdersPurchaseOperateLog;
use app\model\WaPurchaseOrdersExamineApproveFlow;
use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaMembers;
use app\model\WaRules;
use app\model\WaPurchaseOrdersExamineApprove;
use app\model\WaAdminRoles;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;

class PurchaseOrdersApproveController extends Validate
{

    /**
     * 采购订单审批 -列表-分页
     * @param Request $request
     * @return mixed
     */
    public function purchaseOrdersApproveList(Request $request)
    {
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 获取的是 采购审批id  因为记录不删 订单编号会存在重复
        $purchaseOrdersn = WaPurchaseOrdersExamineApproveFlow::allIn($adminId);
        $purchaseOrdersn = json_decode($purchaseOrdersn);
        $fields = ['*'];
        $condition = [];
        $between = [];
        $whereNotIn = [];
//        $whereNotIn = [3];
        if ($param['status']) {
            if ($param['status'] == 4){
                $condition [] = ['status', '!=', 3];
            }else{
                $condition [] = ['status', '=', $param['status']];
            }
        }else{
            if ($param['status'] == 0){
                $condition [] = ['status', '=', $param['status']];
            }else{
                $condition [] = ['status', '!=', 3];
            }
        }
        if ($param['purchase_order_sn']) {
            $condition [] = ['purchase_order_sn', 'like', '%' . $param['purchase_order_sn'] . '%']; // 供应商名称
        }

        if ($param['supplier_name']) {
            $condition [] = ['supplier_name', 'like', '%' . $param['supplier_name'] . '%']; // 供应商名称
        }
        if ($param['initiator_admin_name']) {
            $condition [] = ['initiator_admin_name', 'like', '%' . $param['initiator_admin_name'] . '%'];
        }


        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $rule = WaPurchaseOrdersExamineApprove::list($param, $adminId,$page, $pageNum,$whereNotIn,$purchaseOrdersn, $fields, $condition, $between);

        return IndexController::successed($rule, '采购订单审批列表');
    }



    /**
     * 采购订单待审批 - 审批人 - 列表
     * 不分页 限制10条
     * @param Request $request
     * @return \support\Response
     */
    public function purchaseOrdersWaitApproveByAdminIdList(Request $request)
    {
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 获取的是 采购审批id  因为记录不删 订单编号会存在重复
        $purchaseOrdersn = WaPurchaseOrdersExamineApproveFlow::allIn($adminId);
        $purchaseOrdersn = json_decode($purchaseOrdersn);
//        $purchaseOrdersn = [];
        $fields = ['*'];
        $condition = [];
        $between = [];



        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $rule = WaPurchaseOrdersExamineApprove::waitApproveByAdminIdList($adminId,$page, $pageNum,$purchaseOrdersn, $fields, $condition, $between);

        return IndexController::successed($rule, '采购订单审批列表');
    }



    /**
     * 采购订单审批-状态修改
     * 采购单状态0 草稿 1审批中 2待签署审批合同 3 待请款车款 4待供应商开票 5待配车 6已完成 7已作废 8删除
     * 采购单审批状态 0 审批中 1 通过 2 驳回 3作废 4删除
     * 采购单审批详情状态 0审批中 1审批通过2 审批驳回  3作废  4  删除
     * 退回草稿 正常是审批驳回 ：修改 采购订单状态为 草稿 (撤销审批，审批作废) -> 添加采购订单审批详情记录  ->(是否同步已通知人的 通知消息)
     * @param Request $request
     * @return \support\Response
     */
    public function purchaseOrdersApproveStatus(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
//        $condition []= ['po_no', '=', $param['po_no']];
        $adminId = json_decode(adminId($request));
        if (array_key_exists('refuse_reason',$param)){
            $refuse_reason = $param['refuse_reason'];
        }else{
            $refuse_reason = '';
        }

        // 当前采购单审批订单数据
        $approves = WaPurchaseOrdersExamineApprove::find($adminId,['id' => $param['id']]);
        $approves = json_decode($approves);
        if (!$approves){
            return IndexController::errored('','找不到该采购订单');
        }
        $flow= [];// 当前部门审批流
        $flow_next = []; // 下级部门审批流
        // 当前订单审批流
        $flows = WaPurchaseOrdersExamineApprove::find($adminId,['id' => $param['id']]);
        $flows = json_decode($flows);
        if (!$flows){
            return IndexController::errored('', '未获取采购订单的审批流');
        }
        // 获取订单中的审批流设置
        $flows->approve_flow = json_decode($flows->approve_flow);

        $condition_flow = [];
        $condition_flow [] = ['po_no', '=', $approves->po_no];
        $condition_flow [] = ['status', '=', 0];
        $approve_flow = WaPurchaseOrdersExamineApproveFlow::find($condition_flow);
        $approve_flow = json_decode($approve_flow);
        if (!$approve_flow) {
            return IndexController::errored('', '找不到该审批的待审批记录');
        }else{
            if (!in_array($adminId->id, json_decode($approve_flow->admin_ids))){
                return IndexController::errored('', '当前审批你没有审批权限');
            }

            foreach ($flows->approve_flow as $k) {
                //获取合同中该用户部门的 审批流
                if ($approve_flow->admin_ids ==  json_encode($k->approve_admin_id)) {
                    $flow = $k;
                }
            }

            if (!$flow) {
                return IndexController::errored('ErrorApproveSetting', '当前用户所在部门未设置审批流程，无法提交审批');
            }


        }

        \support\Db::beginTransaction();
        try {
            if ($param['status'] == 0){
                return IndexController::errored('','审批只有通过和驳回状态哦');
            }elseif ($param['status'] == 1){
                // 审批通过 判断审批流是否走到最后一步
                if ($approves){
                    // 首先这订单必须是审批中的状态
                    if($approves->status != 0){
                        return IndexController::errored('','订单不是审批状态无法审批');
                    }

                    if ($approves->approve_flow){

//                    foreach (json_decode($approves->approve_flow) as $k){
                        // 然后判断 当前部门是否审批过 循环所有 审批流的所有部门 正常是按正序循环 找出上级部门为 0 的部门
                        //先查找是否有审批记录 按流程每一个审批操作会自动创建下一个 一条审批或待审批数据
                        $data = [];
                        $data [] = ['check_id', '=', $param['id']];
                        $data [] = ['status', '=', 0];
                        $check_parent = WaPurchaseOrdersExamineApproveFlow::find($data);
                        $check_parent =json_encode($check_parent);
                        // 只有查到待审批数据的部门才有审批权限
                        if ($check_parent){
                            $approve_log_condition = [];
                            $approve_log_condition [] = ['po_no', '=', $approves->po_no];
                            $approve_log_condition [] = ['status', '=', 0];
                            $approve_log_condition [] = ['admin_ids', '=', $approve_flow->admin_ids];
                            // 添加采购单审批详情记录
                            $approve_log_data = [
                                'updated_at' => dateTime(),
                                'admin_id' => $adminId->id,
                                'admin_name' => $adminId->nickname,
                                'refuse_reason' => $refuse_reason,
                                'status' => 1, //0 待审批 1审批通过 2 审批驳回
                            ];
                            if ($approves->purchase_order_sn) {
                                $approve_log_data['purchase_order_sn'] = $approves->purchase_order_sn;// 采购订单编号
                            }
                            $up_purchase_flow_status = WaPurchaseOrdersExamineApproveFlow::updated($approve_log_condition, $approve_log_data); // 添加采购单审批详情记录
                            if (!$up_purchase_flow_status){
                                return IndexController::errored('','审批流日志创建失败');
                            }

                            // 判断审批流到哪一步 如果结束则 修改订单状态 创建合同
                            //判断是否是最后一级审批
                            if ($flow->next_sort == 0){
                                // 最后一级审批  则修改订单审批状态
                                // 销售订单直接创建的采购单
                                $up_purchase_approve_status =WaPurchaseOrdersExamineApprove::updated(['id' => $param['id']],['status' => 1,'updated_at' => dateTime()]); // 修改采购审批单状态
                                if (!$up_purchase_approve_status){
                                    return IndexController::errored('','采购订单审批状态修改失败');
                                }

                                // 由采购单状态修改
                                // 订单状态 0 草稿 1待核验   2审批中   3 待签署销售合同   4 待支付定金 12 财务确认到账 5 订单采购中  13 报关 7待发货   6待支付余款 16 待财务确认余款到账  8待收货  9 已完成 (交付提单/交车) 10 已作废 11 删除
                                // 0 草稿 1审批中 2待签署审批合同 3 待请款车款 4待供应商开票 5待配车 6已完成 7已作废 8删除 9审批驳回 10 审批通过
                                if ($approves->purchase_order_sn){
                                    $up_purchase_status = WaOrdersPurchase::updated(['purchase_orders_status' => 2,'updated_at' => dateTime()],['purchase_order_sn' => $approves->purchase_order_sn ]);
                                    if (!$up_purchase_status){
                                        return IndexController::errored('','采购订单状态修改失败');
                                    }
                                }

                                // 添加 采购订单日志
                                $purchase_operate_log = [
                                    'purchase_order_sn_parent' => $approves->purchase_order_sn,
                                    'status' => 2,
                                    'describe' => '采购订单审批通过',
                                    'remark' => '',
                                    'reason' => '',
                                    'admin_id' => $adminId->id,
                                    'admin_name' => $adminId->nickname,
                                    'created_at' => dateTime(),
                                ];
                                $ordersOperateLog = WaOrdersPurchaseOperateLog::created($purchase_operate_log);
                                if (!$ordersOperateLog){
                                    return IndexController::errored('','采购订单日志操作失败');
                                }

                                // 创建采购合同 需要手动点击不能自动创建

                            }else{

                                $next_sort = $flow->next_sort; //下一级部门
                                foreach ($flows->approve_flow as $k){
                                    //获取订单中该用户部门的 审批流
                                    if ($k->sort == $next_sort) {
                                        $flow_next = $k;
                                    }

                                }
                                if($flow_next){
                                    // 创建下一级待审批流程
                                    $admin_name ='';
                                    if ($flow_next->approve_admin_id){
                                        foreach ($flow_next->approve_admin_id as $apadid) {
                                            $admins = WaAdmins::find(['id' => $apadid]);
                                            $admins = json_decode($admins);
                                            if ($admins) {
                                                $admin_name = $admin_name .'/'. $admins->nickname;
                                            }
                                        }

                                    }

                                    // 添加采购单审批详情记录
                                    $approve_log_data = [
                                        'po_no' => $approves->po_no, // 采购订单编号
                                        'check_id' => $approves->id, // 审批id
                                        'created_at' => dateTime(),
                                        'admin_id' => $adminId->id,
                                        'admin_ids' => json_encode($flow_next->approve_admin_id), //
                                        'admin_name' => $admin_name,
                                        'status' => 0, //0 待审批 1审批通过 2 审批驳回
                                    ];
                                    if ($approves->purchase_order_sn) {
                                        $approve_log_data['purchase_order_sn'] = $approves->purchase_order_sn;// 采购订单编号
                                    }

                                    $up_purchase_flow_status = WaPurchaseOrdersExamineApproveFlow::create($approve_log_data); // 添加销售合同审批详情记录
                                    if (!$up_purchase_flow_status){
                                        return IndexController::errored('','审批流日志创建失败');
                                    }
                                    $time = date('H:i:s', time());
                                    $admin_ids = $flow_next->approve_admin_id;
                                    // 钉钉消息通知
                                    if ($admin_ids){
                                        foreach ($admin_ids as $kadmin){
                                            $admin_condition = [];
                                            $admin_condition [] = ['id','=',$kadmin];
                                            $admin_data = WaAdmins::find($admin_condition);
                                            $admin_data = json_decode($admin_data);
                                            $data = [
                                                'mobile' => $admin_data->mobile,
                                                'title' => '采购订单审批', // 标题
                                                'markdown' => '采购订单审批'.$time, // 内容
                                            ];
                                            $currentRoute  = $request->host();

                                            // 消息通知
                                            if ( $currentRoute == 'frontforeign.olivenev.com'){
                                                $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                                            }
                                        }

                                    }
                                }

                            }

                        }else{
                            return IndexController::errored('','不满足操作条件,请查看订单审批状态 和 审批权限');
                        }

//                    }
                    }
                }

            }elseif ($param['status'] == 2){


                // 审批驳回 修改：采购订单状态为 审批驳回 添加审批驳回的理由两边都要 添加采购订单审批详情记录
                // 审批驳回驳回后是创建新的审批流  旧的失败记录保留
                // 销售订单直接创建的采购单
                $up_purchase_approve_status =WaPurchaseOrdersExamineApprove::updated(['id' => $param['id'] ],['status' => 2,'refuse_reason' => $param['refuse_reason'],'updated_at' => dateTime()]); // 修改采购审批单状态
                if (!$up_purchase_approve_status){
                    return IndexController::errored('','采购订单审批状态修改失败');
                }
                // 添加采购单审批详情记录
                $approve_log_data = [
                    'po_no' => $approves->po_no, // 采购订单编号
                    'check_id' => $approves->id, // 审批id
                    'created_at' => dateTime(),
                    'admin_id' => $adminId->id,
                    'admin_ids' => json_encode($flow->approve_admin_id), //
                    'admin_name' => $adminId->nickname,
                    'refuse_reason' => $refuse_reason,
                    'status' => 2, //0 待审批 1审批通过 2 审批驳回 3作废 4  删除
                ];
                if ($approves->purchase_order_sn) {
                    $approve_log_data['purchase_order_sn'] = $approves->purchase_order_sn;// 采购订单编号
                }
                $approve_log_data['refuse_reason'] = $param['refuse_reason'];
                $up_purchase_flow_status = WaPurchaseOrdersExamineApproveFlow::create($approve_log_data); // 添加采购单审批详情记录
                if (!$up_purchase_flow_status){
                    return IndexController::errored('','采购订单审批流记录创建失败');
                }
                //采购单状态 0 草稿(撤回审批)  1审批中(提交审批) 2待签署审批合同 3 待请款车款 4待供应商开票 5待配车(确认开票) 6已完成 7已作废(作废) 8删除 9 审批驳回 10 审批通过
                $purchase_orders_status = WaOrdersPurchase::updated(['purchase_orders_status' => 9,'refuse_reason' => $param['refuse_reason'],'updated_at' => dateTime()],['purchase_order_sn' => $approves->purchase_order_sn]); // 审批驳回
                $purchase_orders_status = json_decode($purchase_orders_status);
                if (!$purchase_orders_status){
                    return IndexController::errored('','采购订单状态修改失败');
                }
            }else {
                return IndexController::errored('', '采购订单审批状态没有此状态');
            }
            \support\Db::commit();
            return IndexController::successed('', '采购订单审批状态修改成功');
        } catch (\Throwable $exception) {
            IndexController::logError('purchaseOrdersApproveStatus', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '采购订单审批状态修改失败');
        }
    }

    /**
     * 采购订单审批-详情
     */
    public function purchaseOrdersApproveDetail(Request $request){

//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $purchase_order_approve = WaPurchaseOrdersExamineApprove::find($adminId,['purchase_order_sn' => $param['purchase_order_sn'],
            ['po_no','=', $param['po_no']]]);
//        ,['status', '!=', 3]
        $purchase_order_approve = json_decode($purchase_order_approve);

        // 获取审批数据 审批
        if ($purchase_order_approve){
            $purchase_order_approve->approve_flow = json_decode($purchase_order_approve->approve_flow);// 设置的审批流
            foreach ($purchase_order_approve->approve_flow as $kapprove) {
                $admin_name ='';
                if ($kapprove->approve_admin_id){
                    foreach ($kapprove->approve_admin_id as $apadid) {
                        $admins = WaAdmins::find(['id' => $apadid]);
                        $admins = json_decode($admins);
                        if ($admins) {
                            $department = WaDepartment::find(['id' => $admins->department_id]);
                            $department = json_decode($department);
                            if ($department){
                                $admin_name = $admin_name .'/'. $admins->nickname .'('. $department->name .')';

                            }else{
                                $admin_name = $admin_name .'/'. $admins->nickname;

                            }
                        }
                    }

                }


                $kapprove->check_time = dateTime();
                $kapprove->refuse_reason = '';
                $kapprove->status = 0;
                $kapprove->status_name = '待审批';
                $kapprove->admin_name = $admin_name;

            }

            if ($purchase_order_approve->initiator_admin_id){
                $admins = WaAdmins::find(['id' => $purchase_order_approve->initiator_admin_id]);
                $admins = json_decode($admins);
                if ($admins) {
                    $department = WaDepartment::find(['id' => $admins->department_id]);
                    $department = json_decode($department);
                    if ($department){
                        $purchase_order_approve->initiator_admin_name = $purchase_order_approve->initiator_admin_name .'('. $department->name .')';
                    }
                }
            }
            // 采购单审批状态 0 审批中 1 通过 2 驳回 3 作废 4删除
            if ($purchase_order_approve->status == 0){
                $purchase_order_approve->status_name = '审批中';
            }elseif ($purchase_order_approve->status == 1){
                $purchase_order_approve->status_name = '通过';
            }elseif ($purchase_order_approve->status == 2){
                $purchase_order_approve->status_name = '驳回';
            }elseif ($purchase_order_approve->status == 3){
                $purchase_order_approve->status_name = '已撤回';
            }elseif ($purchase_order_approve->status == 4) {
                $purchase_order_approve->status_name = '删除';
            }else{
                $purchase_order_approve->status_name = '';
            }
            // 审批进度
            if ($purchase_order_approve->id){
//                $purchase_approve_flow = WaPurchaseOrdersExamineApproveFlow::all(['check_id' => $purchase_order_approve->id]);
                $purchase_approve_flow = WaPurchaseOrdersExamineApproveFlow::all(['po_no' => $purchase_order_approve->po_no]);
                $purchase_approve_flow = json_decode($purchase_approve_flow);
                if ($purchase_approve_flow){
                    foreach ($purchase_approve_flow as $approve){ // 审批记录

                        // 状态
                        if ($approve->status == 0){
                            $approve->status_name = '审批中';
                        }elseif ($approve->status == 1){
                            $approve->status_name = '审批通过';
                            if ($purchase_order_approve->approve_flow) { // 设置的审批流
//
                                foreach ($purchase_order_approve->approve_flow as $kapprove) {
                                    if (in_array($approve->admin_id,$kapprove->approve_admin_id) && $approve->status == 1 ){
                                        $kapprove->admin_name = $approve->admin_name;
                                        $kapprove->check_time = $approve->updated_at;
                                        $kapprove->refuse_reason = $approve->refuse_reason;
                                        $kapprove->status = $approve->status;
                                        $kapprove->status_name = $approve->status_name;

                                    }
                                }
                            }

                        }elseif ($approve->status == 2){
                            $approve->status_name = '审批驳回';
                            if ($purchase_order_approve->approve_flow) {
                                foreach ($purchase_order_approve->approve_flow as $kapprove) {
                                    if (in_array($approve->admin_id,$kapprove->approve_admin_id)  && $approve->status == 2){
                                        $kapprove->admin_name = $approve->admin_name;
                                        $kapprove->check_time = $approve->created_at;
                                        $kapprove->refuse_reason = $approve->refuse_reason;
                                        $kapprove->status = $approve->status;
                                        $kapprove->status_name = $approve->status_name;

                                    }
                                }
                            }
                        }elseif ($approve->status == 3){
                            $approve->status_name = '已撤回';
                            if ($purchase_order_approve->approve_flow) {
                                foreach ($purchase_order_approve->approve_flow as $kapprove) {
                                    if (in_array($approve->admin_id,$kapprove->approve_admin_id)  && $approve->status == 3){
                                        $kapprove->admin_name = $approve->admin_name;
                                        $kapprove->check_time = $approve->created_at;
                                        $kapprove->refuse_reason = $approve->refuse_reason;
                                        $kapprove->status = $approve->status;
                                        $kapprove->status_name = $approve->status_name;

                                    }
                                }
                            }
                        }elseif ($approve->status == 4) {
                            $approve->status_name = '删除';
                        }elseif ($approve->status == 5) {
                            $approve->status_name = '撤回 ';
                        }else{
                            $approve->status_name = '';
                        }

                    }



                    $purchase_order_approve->initiator = $purchase_approve_flow[0];
                }
                $purchase_order_approve->purchase_approve_flow = $purchase_approve_flow;
            }else{
                $purchase_order_approve->purchase_approve_flow = [];
                $purchase_order_approve->initiator = '';
            }

        }else{
            return IndexController::errored('','获取采购审批数据失败');
        }

        return IndexController::successed(json_encode($purchase_order_approve),'');
    }


}